﻿<%--
Ejemplos usados:
http://examples1.ext.net/#/GridPanel/Editable/Editor_with_DirectMethod/
http://examples1.ext.net/#/GridPanel/Restful/Overview/
--%>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Asiento2.aspx.cs" Inherits="IU.Contabilidad.Asiento.Asiento2" %>
<%@ Register assembly="Ext.Net" namespace="Ext.Net" tagprefix="ext" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Store1_RefershData(object sender, StoreRefreshDataEventArgs e)
    {
        this.CargarDatosEnGrid();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Asiento</title>
      
    <script type="text/javascript">
        var template = '<span style="color:{0};">{1}</span>';

        var change = function(value) {
            return String.format(template, (value > 0) ? "green" : "red", value);
        };

        var pctChange = function(value) {
            return String.format(template, (value > 0) ? "green" : "red", value + "%");
        };
        
        var puedoAgregar = function() {
            var grid = GridPanel1;
            for (var i = 0; i < grid.store.getTotalCount(); i++) {
                var debe = grid.store.getAt(i).get('Debe');
                var haber = grid.store.getAt(i).get('Haber');
                
                if(debe == 0 && haber == 0)
                {
                    alert('No debe haber ningún asiento con debe y haber en cero.');
                    return false;
                }
            }
            return true;
        };

        var startEditing = function(e) {
            if (e.getKey() === e.ENTER) {
                var grid = GridPanel1,
                    record = grid.getSelectionModel().getSelected(),
                    index = grid.store.indexOf(record);

                grid.startEditing(index, 1);
            }
        };

        var calcularBalance = function() {
            var labels = LabelTotales;
            var grid = GridPanel1;
            var debe = 0;
            var haber = 0;
            
            for (var i = 0; i < grid.store.getTotalCount(); i++) {
                debe += grid.store.getAt(i).get('Debe');
                haber += grid.store.getAt(i).get('Haber');
            }

            return [debe, haber, debe - haber];
        }

        /*
         *  Valida el balance y los datos de los valores.
         */
        var balanceValido = function() {
            var labels = LabelTotales;
            var grid = GridPanel1;
            var debe = 0;
            var haber = 0;
            for (var i = 0; i < grid.store.getTotalCount(); i++) {
                debe += grid.store.getAt(i).get('Debe');
                haber += grid.store.getAt(i).get('Haber');
                
                var str = grid.store.getAt(i).get('Cuenta');
                if(str == "" || str == null)
                    return false;
            }

            var res = [debe, haber, debe - haber];
   
            return res[0] > 0 && res[2] == 0;
        }
    
        var actualizarBalance = function() {
            var labels = LabelTotales;
            var grid = GridPanel1;
            var debe = 0;
            var haber = 0;
            for (var i = 0; i < grid.store.getTotalCount(); i++) {
                debe += grid.store.getAt(i).get('Debe');
                haber += grid.store.getAt(i).get('Haber');
            }
            labels.setText("Total debe: " + debe + "     Total haber: " + haber + "     Balance: " + (debe - haber));
        }

        var registrarAsiento = function() {
            var grid = GridPanel1;           
            var datos = "",
                arr = [];
            
            for (var i = 0; i < grid.store.getTotalCount(); i++) 
            {
                arr.push(
                    [
                        grid.store.getAt(i).get('Cod'),
                        grid.store.getAt(i).get('Cuenta'),
                        grid.store.getAt(i).get('Descripcion'),
                        grid.store.getAt(i).get('Debe'),
                        grid.store.getAt(i).get('Haber'),
                    ].join('\r')
                );
            }
            
            datos = arr.join("|");
            
            /*datos += grid.store.getAt(0).get('Cod') + '\r' 
                + grid.store.getAt(0).get('Cuenta') + '\r' 
                + grid.store.getAt(0).get('Descripcion') + '\r' 
                + grid.store.getAt(0).get('Debe') + '\r' 
                + grid.store.getAt(0).get('Haber') + '\r' 
                + i;
            for (var i = 1; i < grid.store.getTotalCount(); i++) 
            {
                datos += "|" + grid.store.getAt(i).get('Cod') + '\r' 
                        + grid.store.getAt(i).get('Cuenta') + '\r' 
                        + grid.store.getAt(i).get('Descripcion') + '\r' 
                        + grid.store.getAt(i).get('Debe') + '\r' 
                        + grid.store.getAt(i).get('Haber') + '\r' 
                        + i;
            }*/
            Ext.net.DirectMethods.RegistrarTodo(datos, TextFieldDescrip.getRawValue(), DateFieldAsiento.getRawValue());
        }

        var afterEdit = function(e) {
            /*
            Properties of 'e' include:
            e.grid - This grid
            e.record - The record being edited
            e.field - The field name being edited
            e.value - The value being set
            e.originalValue - The original value for the field, before the edit.
            e.row - The grid row index
            e.column - The grid column index
            */

            // Call DirectMethod
            //            if(e.record.data.Cod != null)
            //                    CompanyX.AfterEdit(e.record.data.Cod, e.field, e.originalValue, e.value, e.record.data);
            //                else
            //                    CompanyX.AfterEdit(-1, e.field, e.originalValue, e.value, e.record.data);
            var grid = GridPanel1;
            var storeC = StoreCuenta;
            
            /* Habilita o deshabilita el botón de confirmar asiento */
            if (!balanceValido()) {
                BotonConfirmar.disable();
            }
            else {
                BotonConfirmar.enable();
            }

            /* Habilita o deshabilita el botón de confirmar asiento */
            for (var i = 0; i < grid.store.getTotalCount(); i++) {
                grid.store.getAt(i).set('Cod', i + 1);
            }
            if (e.field == "Debe") {
                grid.store.getAt(e.row).set('Haber', 0);
                actualizarBalance();
            }
            else if (e.field == "Haber") {
                grid.store.getAt(e.row).set('Debe', 0);
                actualizarBalance();
            }
            else if (e.field == "Cuenta") {
                grid.store.getAt(e.row).set('Descripcion',
                   storeC.getById(e.value).get('nombre')
                );
            }
            grid.store.commitChanges();
        };
    </script>
</head>
<body>
    <ext:ResourceManager ID="ResourceManager1" runat="server"></ext:ResourceManager>
     
    <ext:Store 
        ID="StoreCuenta" 
        runat="server" 
        >
        <Reader>
            <ext:ArrayReader IDProperty="id">
                <Fields>
                    <ext:RecordField Name="id" Type="String"/>
                    <ext:RecordField Name="nombre" Type="String"/>
                    <ext:RecordField Name="display" Type="String"/>
                </Fields>
            </ext:ArrayReader>
        </Reader>          
    </ext:Store>   
        
    <ext:Store ID="StoreComboMov" runat="server" >
        <Reader>
            <ext:ArrayReader>
                <Fields>
                    <ext:RecordField Name="id" Type="String"/>
                </Fields>
            </ext:ArrayReader>
        </Reader>          
    </ext:Store>   
    
    <ext:Store  ID="Store1" runat="server"
        ShowWarningOnFailure="false"
        UseIdConfirmation="false" 
        OnRefreshData="Store1_RefershData">
        <Reader>
            <ext:JsonReader IDProperty="Cod">
            </ext:JsonReader>
        </Reader>
    </ext:Store>
    
    <ext:Viewport ID="Viewport1" runat="server" AutoScroll="true">
    <Items>
        <ext:Panel 
        Collapsible="true"
        ID="Panel1" 
        runat="server" 
        Title="Asiento"
        Layout="Fit"
        AnchorHorizontal="right"
        >
        <Items>
            <ext:Panel 
            ID="Panel3"
            runat="server" 
            Border="false" 
            Header="false" 
            AutoHeight="true"
            >
                <Items>
                    <ext:FormPanel 
                        ID="FormPanel1" 
                        runat="server" 
                        Title=""
                        MonitorPoll="500" 
                        MonitorValid="true" 
                        Padding="5" 
                        Height="70"
                        ButtonAlign="Right"
                        Border="false"
                        Layout="Column">
                        <Items>
                            <ext:Panel ID="Panel4" 
                                runat="server" 
                                Border="false" 
                                Header="false" 
                                ColumnWidth=".5" 
                                Layout="Form" 
                                LabelAlign="Left">
                                <Defaults>
                                    <ext:Parameter Name="MsgTarget" Value="side" />
                                </Defaults>
                                <Items>                                        
                                    <%-- Antes se llamaba concepto --%>
                                    <ext:TextField ID="TextFieldNombre" runat="server" 
                                        FieldLabel="Nombre" 
                                        AllowBlank="false"
                                        AnchorHorizontal="90%" />
                                                                            
                                    <ext:TextField ID="TextFieldDescrip" runat="server" 
                                        FieldLabel="Descripción" 
                                        AllowBlank="false"
                                        AnchorHorizontal="90%" />
                                </Items>
                            </ext:Panel>
                            <ext:Panel ID="Panel5" 
                                runat="server" 
                                Border="false" 
                                Layout="Form" 
                                ColumnWidth=".5" 
                                LabelAlign="Left">
                                <Defaults>
                                    <ext:Parameter Name="AllowBlank" Value="false" Mode="Raw" />
                                    <ext:Parameter Name="MsgTarget" Value="side" />
                                </Defaults>
                                <Items>
                                    <ext:DateField  
                                        ID="DateFieldAsiento"
                                        runat="server" 
                                        FieldLabel="Fecha" 
                                        Format="dd/MM/yyyy"
                                        AnchorHorizontal="90%" >
                                    </ext:DateField>

                                </Items>
                            </ext:Panel>
                        </Items>
                        <Listeners>
                            <ClientValidation Handler="if(valid && balanceValido()){#{BotonConfirmar}.enable();}else{#{BotonConfirmar}.disable();}" />
                        </Listeners>
                    </ext:FormPanel>
                </Items>
            </ext:Panel>
        </Items>
        </ext:Panel>
        
        <ext:Panel 
            Collapsible="false"
            ID="Panel2" 
            Title="Movimientos"
            runat="server" 
            Border="false"
            Layout="Fit"
            AnchorHorizontal="right"
        >
        <Items>
            <ext:GridPanel ID="GridPanel1" runat="server" StoreID="Store1" Border="false" Height="400">
                <ColumnModel ID="ColumnModel1" runat="server">
                    <Columns>
                        <ext:Column ColumnID="Cod" Header="Código" DataIndex="Cod" Editable="true" Hidden="true">
                        </ext:Column>
                        <ext:Column Header="Cuenta" DataIndex="Cuenta" Editable="true">
                            <Editor>
                                <ext:ComboBox runat="server" 
                                    StoreID="StoreCuenta" 
                                    Editable="true"
                                    DisplayField="display"
                                    ValueField="id"
                                    TypeAhead="true" 
                                    Mode="Local"
                                    ForceSelection="true"
                                    TriggerAction="All"
                                    SelectOnFocus="true">
                                </ext:ComboBox>
                            </Editor>
                        </ext:Column>
                        <ext:Column 
                            Header="Descripción" 
                            DataIndex="Descripcion" 
                            Width="150">
                        </ext:Column>
                        <ext:Column Header="Debe" DataIndex="Debe" Editable="true">
                            <Renderer Format="UsMoney"/>
                            <Editor>
                                <ext:NumberField ID="NumberFieldDebe" runat="server">
                                <DirectEvents>
                                </DirectEvents>
                                </ext:NumberField>
                            </Editor>
                        </ext:Column>
                        <ext:Column Header="Haber" DataIndex="Haber" Editable="true">
                            <Renderer Format="UsMoney"/>
                            <Editor>
                                <ext:NumberField ID="NumberFieldHaber" runat="server">
                                <DirectEvents>
                                </DirectEvents>
                                </ext:NumberField>
                            </Editor>
                        </ext:Column>
                    </Columns>
                </ColumnModel>
                <SelectionModel>
                    <ext:RowSelectionModel ID="RowSelectionModel2" runat="server" SingleSelect="true" />
                </SelectionModel>
                <Listeners>
                    <KeyDown Fn="startEditing" />
                    <AfterEdit Fn="afterEdit" />
                </Listeners>
                <Buttons>
                    <ext:Button ID="ButtonAdd" runat="server" Text="Agregar" Icon="Add">
                        <Listeners>
                            <Click Handler="if(puedoAgregar()) { #{GridPanel1}.addRecord(); }" />
                        </Listeners>
                    </ext:Button>

                    <ext:Button ID="ButtonDelete" runat="server" Text="Quitar" Icon="Delete">
                        <Listeners>
                            <Click Handler="#{GridPanel1}.deleteSelected();actualizarBalance();" />
                        </Listeners>
                    </ext:Button>
                </Buttons>
                <LoadMask ShowMask="true" />
            </ext:GridPanel>  
                                        
            <%-- Label de totales --%>
            <ext:Label ID="LabelTotales" runat="server" Text=""></ext:Label>                      
        </Items>
        <Buttons>
            <ext:Button 
                ID="BotonConfirmar" 
                runat="server" 
                Text="Aceptar asiento" 
                Enabled="false">
                <Listeners>
                    <Click Handler="BotonConfirmar.hide();registrarAsiento();" />
                </Listeners>
            </ext:Button>
            <ext:Button 
                ID="BotonLimpiar" 
                runat="server" 
                Text="Cancelar" 
                Enabled="false">
                <DirectEvents>
                    <Click OnEvent="BotonLimpiar_Click">
                        <EventMask Msg="Cancelando..." ShowMask="true" MinDelay="500" />
                    </Click>
                </DirectEvents>
            </ext:Button>
        </Buttons>
        </ext:Panel>
    </Items>
    </ext:Viewport>
    
</body>
</html>
